package com.zjw.socket.demo.starter.messageService.service.impl;

import com.zjw.socket.demo.starter.messageService.service.IConnectSession;
import com.zjw.socket.demo.starter.messageService.Message;
import com.zjw.socket.demo.starter.messageService.MessageParser;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

@Deprecated(since = "now")
public class SocketConnectSession implements IConnectSession {

    private boolean bConnect;
    private final Socket socket;
    private long userId = -1;
    private InputStream inputStream;
    private Thread connectThread;

    public SocketConnectSession(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void writeBytes(byte[] bytes) {
        try {
            socket.getOutputStream().write(bytes);
        } catch (IOException e) {

        }
    }

    @Override
    public void writeMessage(Message message) {
        try {
            socket.getOutputStream().write(MessageParser.toByte(message));
        } catch (IOException e) {
        }
    }

    @Override
    public void disconnect() {
        if (!bConnect) {
            return;
        }
        try {
            bConnect = false;
            socket.close();
            inputStream = null;
            connectThread.interrupt();
        } catch (IOException e) {
        }
    }

    @Override
    public void reconnect() {

    }

//    @Override
//    public void connect(IConnectSession.IConnectListener connectListener) {
//        try {
//            this.connectListener = connectListener;
//            inputStream = socket.getInputStream();
//            bConnect = true;
//            connectListener.onConnect(this);
//            connectThread = new Thread(() -> {
//                byte[] buffer = new byte[1024];
//                int len;
//                while (!connectThread.isInterrupted()) {
//                    try {
//                        while ((len = inputStream.read(buffer)) != -1) {
//                            connectListener.onMessage(SocketConnectSession.this, Arrays.copyOfRange(buffer, 0, len));
//                        }
//                    } catch (Exception e) {
//                        connectListener.onError(SocketConnectSession.this, e);
//                    }
//                }
//                connectListener.onClose(this);
//            });
//            connectThread.start();
//        } catch (IOException e) {
//            connectListener.onError(this, e);
//        }
//    }
}
